<template>
  <div class="page-content">
    <ElForm :model="queryForm" :inline="true">
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="16">
          <ElSpace :size="1">
            <ElFormItem label="商品名称">
              <ElInput
                v-model="queryForm.keyword"
                placeholder="请输入商品名称"
                clearable
                style="min-width: 180px"
              />
            </ElFormItem>
            <ElFormItem label="商品类型">
              <ElSelect
                v-model="queryForm.type"
                placeholder="请选择商品类型"
                clearable
                style="width: 100%; min-width: 180px"
              >
                <ElOption label="VIP会员" value="vip" />
                <ElOption label="入场券" value="ticket" />
                <ElOption label="实物商品" value="physical" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="状态">
              <ElSelect
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%; min-width: 120px"
              >
                <ElOption label="启用" value="active" />
                <ElOption label="禁用" value="inactive" />
              </ElSelect>
            </ElFormItem>
          </ElSpace>
        </ElCol>

        <ElCol :xs="24" :sm="8" :md="12" :lg="8">
          <ElFormItem>
            <ElSpace :size="12">
              <ElButton type="primary" @click="handleSearch" v-ripple>搜索</ElButton>
              <ElButton @click="resetQuery" v-ripple>重置</ElButton>
              <ElButton type="success" @click="showDialog('add')" v-ripple>新增商品</ElButton>
            </ElSpace>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <ArtTable
      :data="productList"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :show-pagination="true"
      :hide-on-single-page="false"
      index
    >
      <template #default>
        <ElTableColumn label="主图" prop="image" width="80">
          <template #default="scope">
            <ElImage
              v-if="scope.row.image"
              :src="scope.row.image"
              style="width: 50px; height: 50px"
              fit="cover"
              :preview-src-list="[scope.row.image]"
            />
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="商品名称" prop="name" min-width="150" />
        <ElTableColumn label="描述" prop="description" min-width="200" show-overflow-tooltip />
        <ElTableColumn label="价格" prop="price" width="120">
          <template #default="scope">¥{{ (scope.row.price / 100).toFixed(2) }}</template>
        </ElTableColumn>
        <ElTableColumn label="类型" prop="type" width="100">
          <template #default="scope">
            <ElTag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status" width="100">
          <template #default="scope">
            <ElTag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="库存" prop="stock" width="100">
          <template #default="scope">
            <span v-if="scope.row.type === 'physical'">{{ scope.row.stock || 0 }}</span>
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建时间" prop="createTime" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" width="240">
          <template #default="scope">
            <ElButton type="primary" link @click="showDetailDialog(scope.row)">详情</ElButton>
            <ElButton type="primary" link @click="showDialog('edit', scope.row)">编辑</ElButton>
            <ElButton type="danger" link @click="handleDelete(scope.row)">删除</ElButton>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 添加/编辑商品弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商品' : '编辑商品'"
      width="800px"
      align-center
      :close-on-click-modal="false"
    >
      <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 基础信息 -->
        <ElDivider content-position="left">基础信息</ElDivider>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="商品名称" prop="name">
              <ElInput v-model="form.name" placeholder="请输入商品名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="商品类型" prop="type">
              <ElSelect v-model="form.type" placeholder="请选择商品类型" style="width: 100%">
                <ElOption label="VIP会员" value="vip" />
                <ElOption label="入场券" value="ticket" />
                <ElOption label="实物商品" value="physical" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="价格(元)" prop="price">
              <ElInputNumber
                v-model="priceInYuan"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="状态" prop="status">
              <ElSelect v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <ElOption label="启用" value="active" />
                <ElOption label="禁用" value="inactive" />
              </ElSelect>
            </ElFormItem>
          </ElCol>
        </ElRow>
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="排序" prop="sort">
              <ElInputNumber
                v-model="form.sort"
                :min="0"
                style="width: 100%"
                placeholder="请输入排序"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12" v-if="form.type === 'physical'">
            <ElFormItem label="库存" prop="stock">
              <ElInputNumber
                v-model="form.stock"
                :min="0"
                style="width: 100%"
                placeholder="请输入库存"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12" v-if="form.type === 'ticket'">
            <ElFormItem label="票券类型" prop="ticketType">
              <ElInput v-model="form.ticketType" placeholder="请输入票券类型" />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <!-- 图片信息 -->
        <ElDivider content-position="left">图片信息</ElDivider>
        <ElFormItem label="主图片" prop="image">
          <ElUpload
            class="image-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="
              (file) => {
                setUploadType('image')
                return beforeImageUpload(file)
              }
            "
            accept="image/*"
          >
            <ElImage
              v-if="form.image"
              :src="form.image"
              style="width: 100px; height: 100px"
              fit="cover"
            />
            <ElIcon v-else class="image-uploader-icon"><Plus /></ElIcon>
          </ElUpload>
        </ElFormItem>
        <ElFormItem label="图片列表">
          <div class="images-list">
            <div v-for="(image, index) in form.images" :key="index" class="image-item">
              <ElImage :src="image" style="width: 80px; height: 80px" fit="cover" />
              <ElButton
                type="danger"
                size="small"
                circle
                class="remove-btn"
                @click="removeImage(index)"
              >
                <ElIcon><Close /></ElIcon>
              </ElButton>
            </div>
            <ElUpload
              class="image-uploader small"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleImageListSuccess"
              :before-upload="
                (file) => {
                  setUploadType('images')
                  return beforeImageUpload(file)
                }
              "
              accept="image/*"
            >
              <ElIcon class="image-uploader-icon"><Plus /></ElIcon>
            </ElUpload>
          </div>
        </ElFormItem>

        <!-- VIP折扣配置（仅票券类型） -->
        <template v-if="form.type === 'ticket'">
          <ElDivider content-position="left">VIP折扣配置</ElDivider>
          <ElFormItem label="VIP折扣">
            <ElSwitch v-model="enableVipDiscount" @change="handleVipDiscountToggle" />
          </ElFormItem>
          <template v-if="enableVipDiscount && form.vipDiscount">
            <ElRow :gutter="16">
              <ElCol :span="12">
                <ElFormItem label="折扣类型">
                  <ElSelect v-model="form.vipDiscount.type" style="width: 100%">
                    <ElOption label="百分比折扣" value="percent" />
                    <ElOption label="金额减免" value="amount" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="折扣值">
                  <ElInputNumber
                    v-model="form.vipDiscount.value"
                    :min="0"
                    :max="form.vipDiscount.type === 'percent' ? 100 : undefined"
                    style="width: 100%"
                    :placeholder="
                      form.vipDiscount.type === 'percent' ? '请输入折扣百分比' : '请输入减免金额'
                    "
                  />
                  <span style="margin-left: 8px">
                    {{ form.vipDiscount.type === 'percent' ? '%' : '分' }}
                  </span>
                </ElFormItem>
              </ElCol>
            </ElRow>
          </template>
        </template>

        <!-- 商品规格（仅实物商品） -->
        <template v-if="form.type === 'physical'">
          <ElDivider content-position="left">商品规格</ElDivider>
          <ElFormItem label="启用规格">
            <ElSwitch v-model="enableSpecifications" @change="handleSpecificationsToggle" />
          </ElFormItem>
          <template v-if="enableSpecifications && form.specifications">
            <ElFormItem label="规格配置">
              <div class="specifications-container">
                <div
                  v-for="(spec, index) in form.specifications"
                  :key="index"
                  class="specification-item"
                >
                  <div class="specification-header">
                    <span class="specification-title">规格 {{ index + 1 }}</span>
                    <ElButton
                      type="danger"
                      circle
                      size="small"
                      @click="removeSpecification(index)"
                      title="删除规格"
                    >
                      <ElIcon><Delete /></ElIcon>
                    </ElButton>
                  </div>

                  <ElFormItem label="规格名称" :prop="`specifications.${index}.name`">
                    <ElInput
                      v-model="spec.name"
                      placeholder="如：红色大码、36码黑色、XL号短袖等"
                      clearable
                      maxlength="100"
                      show-word-limit
                    />
                  </ElFormItem>

                  <ElRow :gutter="16">
                    <ElCol :span="12">
                      <ElFormItem label="库存数量" :prop="`specifications.${index}.stock`">
                        <ElInputNumber
                          v-model="spec.stock"
                          :min="0"
                          :max="999999"
                          style="width: 100%"
                          placeholder="请输入库存数量"
                        />
                      </ElFormItem>
                    </ElCol>
                    <ElCol :span="12">
                      <ElFormItem
                        label="价格调整(元)"
                        :prop="`specifications.${index}.priceAdjustment`"
                      >
                        <ElInputNumber
                          v-model="spec.priceAdjustmentYuan"
                          :precision="2"
                          style="width: 100%"
                          placeholder="在基础价格上调整"
                          @change="updatePriceAdjustment(index, $event)"
                        />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </div>
                <div class="add-specification-btn">
                  <ElButton type="primary" plain @click="addSpecification" style="width: 200px">
                    <ElIcon><Plus /></ElIcon>
                    添加规格
                  </ElButton>
                </div>
              </div>
            </ElFormItem>
          </template>
        </template>

        <!-- 描述信息 -->
        <ElDivider content-position="left">描述信息</ElDivider>
        <ElFormItem label="商品描述" prop="description">
          <ElInput
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </ElFormItem>
        <ElFormItem label="详细描述" prop="detail">
          <ElInput v-model="form.detail" type="textarea" :rows="4" placeholder="请输入详细描述" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '新增' : '更新' }}
          </ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 商品详情弹窗 -->
    <ElDialog v-model="detailDialogVisible" title="商品详情" width="700px" align-center>
      <div v-if="currentProduct" class="product-detail">
        <ElDescriptions :column="2" border>
          <ElDescriptionsItem label="商品名称">
            {{ currentProduct.name }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="商品类型">
            <ElTag :type="getTypeTagType(currentProduct.type)">
              {{ getTypeLabel(currentProduct.type) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="价格">
            ¥{{ (currentProduct.price / 100).toFixed(2) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="状态">
            <ElTag :type="currentProduct.status === 'active' ? 'success' : 'info'">
              {{ currentProduct.status === 'active' ? '启用' : '禁用' }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="排序">
            {{ currentProduct.sort || 0 }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="库存" v-if="currentProduct.type === 'physical'">
            {{ currentProduct.stock || 0 }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="票券类型" v-if="currentProduct.type === 'ticket'">
            {{ currentProduct.ticketType || '-' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="创建时间">
            {{ formatDate(currentProduct.createTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="更新时间">
            {{ formatDate(currentProduct.updateTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="创建者" v-if="currentProduct.createdBy">
            {{ currentProduct.createdBy }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <!-- 图片展示 -->
        <div class="mt-4">
          <ElDescriptions :column="1" border>
            <ElDescriptionsItem label="主图片">
              <ElImage
                v-if="currentProduct.image"
                :src="currentProduct.image"
                style="width: 100px; height: 100px"
                fit="cover"
                :preview-src-list="[currentProduct.image]"
              />
              <span v-else>-</span>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="图片列表" v-if="currentProduct.images?.length">
              <div class="images-preview">
                <ElImage
                  v-for="(image, index) in currentProduct.images"
                  :key="index"
                  :src="image"
                  style="width: 80px; height: 80px; margin-right: 8px"
                  fit="cover"
                  :preview-src-list="currentProduct.images"
                />
              </div>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品描述">
              {{ currentProduct.description || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="详细描述">
              {{ currentProduct.detail || '-' }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>

        <!-- VIP折扣信息 -->
        <div class="mt-4" v-if="currentProduct.vipDiscount">
          <ElDescriptions :column="2" border title="VIP折扣信息">
            <ElDescriptionsItem label="折扣类型">
              {{ currentProduct.vipDiscount.type === 'percent' ? '百分比折扣' : '金额减免' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="折扣值">
              {{ currentProduct.vipDiscount.value
              }}{{ currentProduct.vipDiscount.type === 'percent' ? '%' : '分' }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>

        <!-- 规格信息 -->
        <div class="mt-4" v-if="currentProduct.specifications?.length">
          <ElDescriptions :column="1" border title="商品规格">
            <ElDescriptionsItem label="规格列表">
              <ElTable :data="currentProduct.specifications" size="small">
                <ElTableColumn label="规格名称" prop="name" />
                <ElTableColumn label="库存" prop="stock" />
                <ElTableColumn label="价格调整" prop="priceAdjustment">
                  <template #default="scope">
                    ¥{{ (scope.row.priceAdjustment / 100).toFixed(2) }}
                  </template>
                </ElTableColumn>
              </ElTable>
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="detailDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules, UploadProps } from 'element-plus'
  import { Plus, Close, Delete } from '@element-plus/icons-vue'
  import {
    ProductService,
    type Product,
    type ProductListParams,
    type CreateProductParams
  } from '@/api/productApi'

  defineOptions({ name: 'ProductManage' })

  // 响应式数据
  const loading = ref(false)
  const submitLoading = ref(false)
  const dialogVisible = ref(false)
  const detailDialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const formRef = ref<FormInstance>()
  const currentProduct = ref<Product | null>(null)
  const originalFormData = ref<CreateProductParams | null>(null)
  const enableVipDiscount = ref(false)
  const enableSpecifications = ref(false)

  // 上传相关
  const uploadAction = ref('/api/v1/admin/upload/image')

  // 待上传文件存储
  const pendingMainImage = ref<File | null>(null)
  const pendingImagesList = ref<File[]>([])
  const tempMainImageUrl = ref<string>('')
  const tempImagesUrlList = ref<string[]>([])

  // 查询表单
  const queryForm = reactive<ProductListParams>({
    keyword: '',
    type: undefined,
    status: undefined,
    sort: undefined,
    stockStatus: undefined
  })

  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })

  // 商品列表
  const productList = ref<Product[]>([])

  // 表单数据
  const form = reactive<CreateProductParams>({
    name: '',
    description: '',
    detail: '',
    price: 0,
    image: '',
    images: [],
    type: 'vip',
    status: 'active',
    sort: 0,
    stock: undefined,
    ticketType: undefined,
    vipDiscount: null,
    specifications: null
  })

  // 价格转换为元的计算属性
  const priceInYuan = computed({
    get: () => form.price / 100,
    set: (value: number) => {
      form.price = Math.round(value * 100)
    }
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
    detail: [{ required: true, message: '请输入详细描述', trigger: 'blur' }],
    price: [
      { required: true, message: '请输入商品价格', trigger: 'blur' },
      { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
    ],
    type: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
    status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    image: [{ required: true, message: '请上传主图片', trigger: 'blur' }]
  })

  // 获取商品列表
  const getProductList = async () => {
    try {
      loading.value = true
      const params: ProductListParams = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm
      }
      const response = await ProductService.getProductList(params)
      console.log('response', response)
      if (response.code == 200) {
        productList.value = response.data
        pagination.total = response.total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取商品列表失败')
      console.error('获取商品列表失败:', error)
      productList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getProductList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      keyword: '',
      type: undefined,
      status: undefined,
      sort: undefined,
      stockStatus: undefined
    })
    pagination.page = 1
    getProductList()
  }

  // 分页处理
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.page = 1
    getProductList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    getProductList()
  }

  // 显示对话框
  const showDialog = (type: 'add' | 'edit', row?: Product) => {
    dialogType.value = type
    dialogVisible.value = true

    if (type === 'edit' && row) {
      const editData: CreateProductParams = {
        name: row.name,
        description: row.description,
        detail: row.detail,
        price: row.price,
        image: row.image,
        images: row.images || [],
        type: row.type,
        status: row.status,
        sort: row.sort,
        stock: row.stock,
        ticketType: row.ticketType,
        vipDiscount: row.vipDiscount,
        specifications:
          row.specifications?.map((spec) => ({
            ...spec,
            priceAdjustmentYuan: spec.priceAdjustment / 100
          })) || null
      }
      Object.assign(form, editData)
      originalFormData.value = { ...editData }
      currentProduct.value = row

      // 设置开关状态
      enableVipDiscount.value = !!row.vipDiscount
      enableSpecifications.value = !!row.specifications
    } else {
      resetForm()
      originalFormData.value = null
      currentProduct.value = null
      enableVipDiscount.value = false
      enableSpecifications.value = false
    }
  }

  // 重置表单
  const resetForm = () => {
    Object.assign(form, {
      name: '',
      description: '',
      detail: '',
      price: 0,
      image: '',
      images: [],
      type: 'vip',
      status: 'active',
      sort: 0,
      stock: undefined,
      ticketType: undefined,
      vipDiscount: null,
      specifications: null
    })

    // 清理待上传文件
    clearPendingFiles()

    formRef.value?.resetFields()
  }

  // 图片上传相关
  const handleImageSuccess: UploadProps['onSuccess'] = () => {
    // 原有的直接上传逻辑已被替换为暂存逻辑
    console.log('Old upload success handler, no longer used')
  }

  const handleImageListSuccess: UploadProps['onSuccess'] = () => {
    // 原有的直接上传逻辑已被替换为暂存逻辑
    console.log('Old upload list success handler, no longer used')
  }

  // 当前上传类型标识
  const currentUploadType = ref<'image' | 'images'>('image')

  const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isImage = rawFile.type.startsWith('image/')
    const isLt2M = rawFile.size / 1024 / 1024 < 2

    if (!isImage) {
      ElMessage.error('只能上传图片文件!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB!')
      return false
    }

    // 生成临时预览URL
    const tempUrl = URL.createObjectURL(rawFile)

    if (currentUploadType.value === 'image') {
      // 处理主图
      pendingMainImage.value = rawFile
      tempMainImageUrl.value = tempUrl
      form.image = tempUrl // 用于预览
    } else {
      // 处理图片列表
      pendingImagesList.value.push(rawFile)
      tempImagesUrlList.value.push(tempUrl)
      form.images.push(tempUrl) // 用于预览
    }

    return false // 阻止自动上传
  }

  const removeImage = (index: number) => {
    // 清理临时URL
    const removedUrl = form.images[index]
    const tempIndex = tempImagesUrlList.value.indexOf(removedUrl)
    if (tempIndex > -1) {
      URL.revokeObjectURL(removedUrl)
      tempImagesUrlList.value.splice(tempIndex, 1)
      pendingImagesList.value.splice(tempIndex, 1)
    }
    form.images.splice(index, 1)
  }

  // 设置上传类型（在模板中调用）
  const setUploadType = (type: 'image' | 'images') => {
    currentUploadType.value = type
  }

  // 清理所有临时文件和URL
  const clearPendingFiles = () => {
    // 清理主图
    if (pendingMainImage.value) {
      if (tempMainImageUrl.value) {
        URL.revokeObjectURL(tempMainImageUrl.value)
      }
      pendingMainImage.value = null
      tempMainImageUrl.value = ''
    }

    // 清理图片列表
    tempImagesUrlList.value.forEach((url) => URL.revokeObjectURL(url))
    pendingImagesList.value = []
    tempImagesUrlList.value = []
  }

  // 生成唯一文件名
  const generateFileName = (file: File, suffix: string = ''): string => {
    const timestamp = Date.now()
    const random = Math.random().toString(36).substring(2, 8)
    const extension = file.name.split('.').pop() || 'jpg'
    return `${timestamp}_${random}${suffix}.${extension}`
  }

  // 准备待上传文件列表
  const preparePendingUploads = () => {
    const pendingUploads: { file: File; fileName: string; fieldType: 'image' | 'images' }[] = []

    // 添加主图
    if (pendingMainImage.value) {
      pendingUploads.push({
        file: pendingMainImage.value,
        fileName: generateFileName(pendingMainImage.value, '_main'),
        fieldType: 'image'
      })
    }

    // 添加图片列表
    pendingImagesList.value.forEach((file, index) => {
      pendingUploads.push({
        file,
        fileName: generateFileName(file, `_list_${index}`),
        fieldType: 'images'
      })
    })

    return pendingUploads
  }

  // 创建商品（集成文件上传）
  const createProduct = async () => {
    try {
      const productData = { ...form }

      // 1. 如果有待上传文件，先执行上传
      const pendingUploads = preparePendingUploads()
      if (pendingUploads.length > 0) {
        ElMessage.info('正在上传图片...')

        const uploadResults = await ProductService.batchUploadFiles(pendingUploads)

        // 将上传结果设置到表单数据中
        if (uploadResults.image) {
          productData.image = uploadResults.image
        }
        if (uploadResults.images && uploadResults.images.length > 0) {
          productData.images = uploadResults.images
        }
      }

      // 2. 创建商品（包含图片信息）
      const createResponse = await ProductService.createProduct(productData)
      console.log('createProduct response', createResponse)

      // 3. 清理临时文件
      clearPendingFiles()

      ElMessage.success('商品创建成功')
    } catch (error) {
      ElMessage.error('创建商品失败')
      console.error('创建商品失败:', error)
      throw error
    }
  }

  // VIP折扣相关
  const handleVipDiscountToggle = (enabled: boolean) => {
    if (enabled) {
      form.vipDiscount = {
        type: 'percent',
        value: 0
      }
    } else {
      form.vipDiscount = null
    }
  }

  // 规格管理相关
  const handleSpecificationsToggle = (enabled: boolean) => {
    if (enabled) {
      form.specifications = []
    } else {
      form.specifications = null
    }
  }

  const addSpecification = () => {
    if (!form.specifications) {
      form.specifications = []
    }
    const newSpec = {
      name: '',
      stock: 0,
      priceAdjustment: 0,
      priceAdjustmentYuan: 0
    }
    form.specifications.push(newSpec)
  }

  const removeSpecification = (index: number) => {
    form.specifications?.splice(index, 1)
  }

  const updatePriceAdjustment = (index: number, value: number) => {
    if (form.specifications && form.specifications[index]) {
      form.specifications[index].priceAdjustment = Math.round(value * 100)
    }
  }

  // 获取变更的数据
  const getChangedData = () => {
    if (!originalFormData.value) return form

    const changes: Partial<CreateProductParams> = {}
    Object.keys(form).forEach((key) => {
      const formKey = key as keyof CreateProductParams
      if (JSON.stringify(form[formKey]) !== JSON.stringify(originalFormData.value![formKey])) {
        changes[formKey] = form[formKey] as any
      }
    })
    return changes
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      if (dialogType.value === 'add') {
        // 创建商品流程
        await createProduct()
      } else {
        // 更新商品流程
        const changes = getChangedData()
        if (Object.keys(changes).length === 0) {
          ElMessage.warning('没有数据变更')
          dialogVisible.value = false
          return
        }
        await ProductService.updateProduct(currentProduct.value!._id!, changes)
        ElMessage.success('商品更新成功')
      }

      dialogVisible.value = false
      getProductList()
    } catch (error) {
      ElMessage.error(dialogType.value === 'add' ? '创建商品失败' : '更新商品失败')
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 删除商品
  const handleDelete = (row: Product) => {
    ElMessageBox.confirm('确定删除该商品吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await ProductService.deleteProduct(row._id!)
        ElMessage.success('删除成功')
        getProductList()
      } catch (error) {
        ElMessage.error('删除失败')
        console.error('删除失败:', error)
      }
    })
  }

  // 显示商品详情
  const showDetailDialog = async (row: Product) => {
    try {
      const response = await ProductService.getProductDetail(row._id!)
      console.log('detail response', response)
      currentProduct.value = response.data
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取商品详情失败')
      console.error('获取商品详情失败:', error)
    }
  }

  // 工具函数
  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      vip: 'VIP会员',
      ticket: '入场券',
      physical: '实物商品'
    }
    return labels[type] || type
  }

  const getTypeTagType = (type: string) => {
    const types: Record<string, string> = {
      vip: 'warning',
      ticket: 'success',
      physical: 'primary'
    }
    return types[type] || 'info'
  }

  const formatDate = (timestamp?: number) => {
    if (!timestamp) return '-'

    try {
      // 处理秒级时间戳
      const date = new Date(timestamp * 1000)

      if (isNaN(date.getTime())) {
        return timestamp.toString() // 如果解析失败，返回原数值
      }

      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
        .replace(/\//g, '-')
    } catch (error) {
      console.error('时间格式化错误:', error, timestamp)
      return timestamp?.toString() || '-'
    }
  }

  // 生命周期
  onMounted(() => {
    getProductList()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .product-detail {
      .mt-4 {
        margin-top: 16px;
      }

      .images-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }
    }

    .image-uploader {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100px;
      height: 100px;
      overflow: hidden;
      cursor: pointer;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      transition: var(--el-transition-duration-fast);

      &.small {
        width: 80px;
        height: 80px;
      }

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .image-uploader-icon {
      width: 28px;
      height: 28px;
      font-size: 28px;
      color: #8c939d;
      text-align: center;
    }

    .images-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .image-item {
        position: relative;

        .remove-btn {
          position: absolute;
          top: -8px;
          right: -8px;
          width: 20px;
          height: 20px;
          min-height: 20px;
        }
      }
    }

    .specifications-container {
      .specification-item {
        padding: 16px;
        margin-bottom: 12px;
        background: var(--el-bg-color-page);
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--el-color-primary-light-3);
          box-shadow: 0 2px 12px rgb(0 0 0 / 8%);
        }

        .specification-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-bottom: 8px;
          margin-bottom: 12px;
          border-bottom: 1px solid var(--el-border-color-lighter);

          .specification-title {
            font-size: 14px;
            font-weight: 500;
            color: var(--el-text-color-primary);
          }
        }

        .el-form-item {
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }
        }

        // 减少规格名称的下边距
        .el-form-item:has(.el-input) {
          margin-bottom: 10px;
        }
      }

      .add-specification-btn {
        display: flex;
        justify-content: center;
        padding: 12px 0;
        margin-top: 16px;
        border-top: 1px dashed var(--el-border-color);
      }
    }
  }
</style>
